//
//  ByLocationCityVC.m
//  mijifen_ios
//
//  Created by 朱凯 on 2017/10/30.
//  Copyright © 2017年 itboye. All rights reserved.
//

#import "ByLocationCityVC.h"


// view
#import "ByViewFastLocation.h"
#import "ByViewCitySearch.h"
#import "ByViewLocationCityReusableHeader.h"

// cell
#import "ByCellLocationCity.h"


@interface ByLocationCityVC () <UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView      *collect;
@property (nonatomic, strong) ByViewFastLocation    *fastLocationView;  // 快速定位视图

@property (nonatomic, strong) NSMutableArray        *allCitys;          // 全部城市model
@property (nonatomic, strong) NSMutableDictionary   *allCityDic;        // 全部城市字典（根据首字母分开）
@property (nonatomic, copy  ) NSArray               *allKeys;           // 全部首字母

@property (nonatomic, strong) NSMutableArray        *filterCitys;       // 全部城市model


@end

@implementation ByLocationCityVC
{
    BOOL _searchIng;    // 是否正在搜索
}

#pragma mark - view mehtod
- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"定位城市";
    self.view.backgroundColor = BY_BG_COLOR;
    
    [self addLeftBackBarButtonItem];
    
    [self createViews];
    
    // 加载城市列表时需要用到首字母获取，较好时（3-5秒），所以这种有了异步加载
    [ByCoreToolAlert showLoadind:@"正在载入城市列表"];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self getCityListFromDBWithCompletionBlock:^{
            [ByCoreToolAlert hideHud];
            // 设置快速定位视图的键名
            _fastLocationView.keys = _allKeys;
            // 刷新
            [self.collect reloadData];
        }];
    });
}

#pragma mark - 获取数据库数据
- (void)getCityListFromDBWithCompletionBlock:(dispatch_block_t)completionBlock {
    
    // 获取所有城市列表
    NSMutableArray *temp = [NSMutableArray new];
    NSArray *p_models = [ByCoreAddressSqlite3 getAllProvinceModel];
    for (ByCoreProvinceModel *p_model in p_models) {
        
        NSArray *c_models = [ByCoreAddressSqlite3 getAllCityModelWithProvinceID:p_model.provinceID];
        [temp addObjectsFromArray:c_models];
    }
    
    // 转换成包含首字母的城市列表
    NSMutableArray *temp2 = [NSMutableArray new];
    for (ByCoreCityModel *c_model in temp) {
        ByModelLocationCity *cityModel = [[ByModelLocationCity alloc] initWithSuper:c_model];
        [temp2 addObject:cityModel];
    }
    self.allCitys = temp2.mutableCopy;
    
    // 需要忽略的城市名
    NSArray *ignoreCitys = @[@"县",
                             @"市",
                             @"市辖区",
                             @"省直辖行政单位",
                             @"省直辖县级行政单位",];
    
    // 组合相同字母的一组中
    NSMutableDictionary *dic = [NSMutableDictionary new];
    for (ByModelLocationCity *cityModel in self.allCitys) {
        
        if ([ignoreCitys containsObject:cityModel.city]) {
            continue;
        }
        
        NSString *str = cityModel.firstLetter;
        if ([dic.allKeys containsObject:str]) {
            NSMutableArray *section = dic[str];
            [section addObject:cityModel];
        } else {
            NSMutableArray *section = [NSMutableArray new];
            [section addObject:cityModel];
            [dic setObject:section forKey:str];
        }
    }
    
    self.allCityDic = dic.mutableCopy;
    
    // 获得交换键名后的数组
    self.allKeys = [self.allCityDic.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSString *key1, NSString *key2) {
        
        if ([key1 compare:key2] == NSOrderedAscending) {
            return NSOrderedAscending;
        } else {
            return NSOrderedDescending;
        }
    }];

    // 完成后回调到主线程
    dispatch_async(dispatch_get_main_queue(), ^{
        completionBlock();
    });
}

#pragma mark - 创建视图
- (void)createViews {
    
    // 城市搜索
    ByViewCitySearch *searchView = [ByViewCitySearch new];
    [self.view addSubview:searchView];
    searchView.searchBlock = ^(NSString *text) {
        [self search:text];
    };
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(@0);
        make.height.equalTo(@60);
    }];
    
    // 快速定位视图
    _fastLocationView = [[ByViewFastLocation alloc] init];
    [self.view addSubview:_fastLocationView];
    __weak typeof(self) wself = self;
    _fastLocationView.fastLocationBlock = ^(NSString *text, NSInteger index) {
        // 点击快速定位，跳转到对应的位置
        [wself.collect scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:index + 3] atScrollPosition:UICollectionViewScrollPositionTop animated:false];
        CGFloat offset = wself.collect.contentOffset.y;
        offset -= 30;
        wself.collect.contentOffset = CGPointMake(0, offset);
    };
    [_fastLocationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@0);
        make.top.equalTo(searchView.mas_bottom);
        make.width.equalTo(@20);
        if (@available(ios 11.0,*)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(@0);
        }
    }];
    
    // 列表
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 5;
    layout.minimumInteritemSpacing = 5;
    layout.itemSize = CGSizeMake((self.view.width - 20 - 5 * 3 - 8 * 2) / 4, 35);
    layout.sectionInset = UIEdgeInsetsMake(0, 8, 0, 8);

    self.collect = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collect.backgroundColor = BY_BG_COLOR;
    self.collect.delegate = self;
    self.collect.dataSource = self;
    [self.view addSubview:self.collect];
    [self.collect mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.top.bottom.equalTo(_fastLocationView);
        make.right.equalTo(_fastLocationView.mas_left);
    }];
    
    [self.collect registerClass:[ByCellLocationCity class] forCellWithReuseIdentifier:@"searchCell"];
    [self.collect registerClass:[ByCellLocationCity class] forCellWithReuseIdentifier:@"locationCell"];
    [self.collect registerClass:[ByCellLocationCity class] forCellWithReuseIdentifier:@"otherCell"];
    [self.collect registerClass:[ByViewLocationCityReusableHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [self.collect registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];

}

#pragma mark - UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    if (_searchIng) {
        return 1;
    } else {
        // 定位城市+最近访问+热门+全部其他（根据首字母）
        return 3 + _allKeys.count;
    }
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (_searchIng) {
        
        return _filterCitys.count;
    } else {
        
        if (section >= 0 && section < 3) {
            return 1;
        } else {
            NSArray *sectionItems = _allCityDic[_allKeys[section - 3]];
            return sectionItems.count;
        }
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_searchIng) {
        
        ByCellLocationCity *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"searchCell" forIndexPath:indexPath];
        ByModelLocationCity *model = _filterCitys[indexPath.row];
        cell.city = model.city;
        return cell;
        
    } else {
        
        if (indexPath.section == 0) {
            ByCellLocationCity *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"locationCell" forIndexPath:indexPath];
            cell.isLocation = true;
            return cell;
        } else {
            ByCellLocationCity *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"otherCell" forIndexPath:indexPath];
            
            if (indexPath.section == 1) {
                
            } else if (indexPath.section == 2) {
                
            } else {
                NSArray *sectionItems = _allCityDic[_allKeys[indexPath.section - 3]];
                ByModelLocationCity *model = sectionItems[indexPath.row];
                cell.city = model.city;
            }
            return cell;
        }
    }
    return UICollectionViewCell.new;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {

    if (_searchIng) {
        return CGSizeZero;
    } else {
        return CGSizeMake(self.view.width, 30);
    }
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    
    if (_searchIng) {
        return CGSizeZero;
    } else {
        if (section == 2) {
            return CGSizeMake(self.view.width, 20);
        } else {
            return CGSizeZero;
        }
    }
    
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if (_searchIng) {
        return nil;
    }
    else {
        // 头视图
        if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
            
            ByViewLocationCityReusableHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
            
            if (indexPath.section == 0) {
                header.title = @"当前定位城市";
            }
            else if (indexPath.section == 1) {
                header.title = @"最近访问城市";
            }
            else if (indexPath.section == 2) {
                header.title = @"热门城市";
            } else {
                header.title = _allKeys[indexPath.section - 3];
            }
            return header;
        }
        // 尾视图
        else {
            
            if (indexPath.section == 2) {
                
                UICollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath];
                [footer.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
                UIView *line = [UIView new];
                line.backgroundColor = BY_LINE_COLOR;
                [footer addSubview:line];
                [line mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(@10);
                    make.bottom.equalTo(@0);
                    make.right.equalTo(@-10);
                    make.height.equalTo(@1);
                }];
                
                return footer;
            }
        }
    }
    
    
    return nil;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:false];
    
    if (_searchIng) {
        self.didSelectCity(_filterCitys[indexPath.row]);
    } else {
        if (self.didSelectCity) {
            if (indexPath.section == 1) {
                
            } else if (indexPath.section == 2) {
                
            } else {
                NSArray *sectionItems = _allCityDic[_allKeys[indexPath.section - 3]];
                ByModelLocationCity *model = sectionItems[indexPath.row];
                self.didSelectCity(model);
            }
        }
    }
    
    [self dismissViewControllerAnimated:true completion:nil];
    
}



#pragma mark - 点击事件
- (void)search:(NSString *)text {
    
    if (text.length == 0) {
        _searchIng = false;
    } else {
        _searchIng = true;
        _filterCitys = [NSMutableArray new];
        for (ByModelLocationCity *model in _allCitys) {
            if ([model.city containsString:text]) {
                [_filterCitys addObject:model];
            }
        }
    }
    [_collect reloadData];

}
@end
